﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using Tizer.Core;
using Tizer.Core.Enums;
using Tizer.Core.Repository;
using Tizer.Utilities;
using Tizer.Web.Backoffice;
using Tizer.Web.Helper.Extension;

namespace Tizer.Web
{
    /// <summary>
    /// Сервис получения списка объектов 
    /// </summary>
    [WebService(Namespace = "http://tizer.by/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class DataService : System.Web.Services.WebService
    {

        /// <summary>
        /// Получение списка аккаунтов
        /// </summary>
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public string GetAccountBy(int sEcho, int iColumns, string sColumns, int iDisplayStart, int iDisplayLength, string sSearch, int iSortCol_0, string sSortDir_0)
        {
            try
            {
                using (var accountRepository = new AccountRepository())
                {
                    SortDir sortDir = (sSortDir_0 == SortDir.DESC.ConvertToString().ToLower()) ? SortDir.DESC : SortDir.ASC;
                    int iTotalDisplayRecords = 0;

                    string sortBy = String.Empty;

                    switch (iSortCol_0)
                    {
                        case 0:
                            sortBy = Reflector.GetPropertyName<Account>(x => x.CreatedDate);
                            break;
                        case 1:
                            sortBy = Reflector.GetPropertyName<Account>(x => x.Login);
                            break;
                        case 2:
                            sortBy = Reflector.GetPropertyName<Account>(x => x.Email);
                            break;
                        case 3:
                            sortBy = Reflector.GetPropertyName<Account>(x => x.IsActive);
                            break;
                        case 4:
                            sortBy = Reflector.GetPropertyName<Account>(x => x.IsApproved);
                            break;
                        case 5:
                            sortBy = Reflector.GetPropertyName<Account>(x => x.Company);
                            break;
                        default:
                            sortBy = Reflector.GetPropertyName<Account>(x => x.ID);
                            break;
                    }

                    var res =
                        from account in accountRepository.GetPage(iDisplayStart, iDisplayLength, sortBy, sortDir, out iTotalDisplayRecords)
                        select new
                        {
                            ID = account.ID,
                            createdDate = account.CreatedDate.ToString("dd/MM/yyyy",System.Globalization.CultureInfo.InvariantCulture),
                            login = account.Login,
                            email = account.Email,
                            isActive = account.IsActive.ToText(),
                            isApproved = account.IsApproved.ToText(),
                            company = string.IsNullOrEmpty(account.Company)  ? BasePage.StrEmpty : account.Company
                        };

                    return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(new
                    {
                        sEcho = sEcho,
                        iTotalRecords = res.Count(),
                        iTotalDisplayRecords = iTotalDisplayRecords,
                        aaData = res.ToArray()
                    });
                }
            }
            catch (Exception exc)
            {
                return exc.ToString();
            }
        }


        /// <summary>
        /// Удаление аккаунта
        /// </summary>
        /// <param name="id">ID аккаунта</param>
        /// <returns>Возвращает "ОК" или текст ошибки</returns>
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public string DeleteAccountById(int id)
        {
            try
            {
                using (var accountRepository = new AccountRepository())
                {
                    accountRepository.Delete(id);
                    return "OK";
                }
            }
            catch (Exception exc)
            {
                return exc.ToString();
            }
        }


        /// <summary>
        /// Получение ссылки на редактирование менеджера
        /// </summary>
        /// <param name="id"></param>
        [WebMethod]
        [ScriptMethod(UseHttpGet = false)]
        public void EditManagerBy(int id)
        {
            var request = (HttpWebRequest)WebRequest.Create(AdminBasePage.UrlAdminAccountEdit + "?id=" + id);
        }

        /// <summary>
        /// Получение списка стран
        /// </summary>
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public string GetCountryBy(int sEcho, int iColumns, string sColumns, int iDisplayStart, int iDisplayLength, string sSearch, int iSortCol_0, string sSortDir_0)
        {
            try
            {
                using (var countryRepository = new CountryRepository())
                {
                    SortDir sortDir = (sSortDir_0 == SortDir.DESC.ConvertToString().ToLower()) ? SortDir.DESC : SortDir.ASC;
                    int iTotalDisplayRecords = 0;

                    string sortBy = String.Empty;

                    switch (iSortCol_0)
                    {
                        case 0:
                            sortBy = Reflector.GetPropertyName<Country>(x => x.Name);
                            break;
                        default:
                            sortBy = Reflector.GetPropertyName<Country>(x => x.ID);
                            break;
                    }

                    var res =
                        from country in countryRepository.GetPage(iDisplayStart, iDisplayLength, sortBy, sortDir, out iTotalDisplayRecords)
                        select new
                        {
                            ID = country.ID,
                            name = string.IsNullOrEmpty(country.Name) ? BasePage.StrEmpty : country.Name
                        };

                    return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(new
                    {
                        sEcho = sEcho,
                        iTotalRecords = res.Count(),
                        iTotalDisplayRecords = iTotalDisplayRecords,
                        aaData = res.ToArray()
                    });
                }
            }
            catch (Exception exc)
            {
                return exc.ToString();
            }
        }


        /// <summary>
        /// Удаление страны
        /// </summary>
        /// <returns>Возвращает "ОК" или текст ошибки</returns>
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public string DeleteCountryById(int id)
        {
            try
            {
                using (var countryRepository = new CountryRepository())
                {
                    countryRepository.Delete(id);
                    return "OK";
                }
            }
            catch (Exception exc)
            {
                return exc.ToString();
            }
        }


        /// <summary>
        /// Получение ссылки на редактирование
        /// </summary>
        /// <param name="id"></param>
        [WebMethod]
        [ScriptMethod(UseHttpGet = false)]
        public void EditCountryBy(int id)
        {
            var request = (HttpWebRequest)WebRequest.Create(AdminBasePage.UrlAdminCountryEdit + "?id=" + id);
        }

        /// <summary>
        /// Получение списка
        /// </summary>
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public string GetCityBy(int sEcho, int iColumns, string sColumns, int iDisplayStart, int iDisplayLength, string sSearch, int iSortCol_0, string sSortDir_0)
        {
            try
            {
                using (var cityRepository = new CityRepository())
                {
                    SortDir sortDir = (sSortDir_0 == SortDir.DESC.ConvertToString().ToLower()) ? SortDir.DESC : SortDir.ASC;
                    int iTotalDisplayRecords = 0;

                    string sortBy = String.Empty;

                    switch (iSortCol_0)
                    {
                        case 0:
                            sortBy = Reflector.GetPropertyName<City>(x => x.Name);
                            break;
                        default:
                            sortBy = Reflector.GetPropertyName<City>(x => x.ID);
                            break;
                    }

                    var res =
                        from city in cityRepository.GetPage(iDisplayStart, iDisplayLength, sortBy, sortDir, out iTotalDisplayRecords)
                        select new
                        {
                            ID = city.ID,
                            name = string.IsNullOrEmpty(city.Name) ? BasePage.StrEmpty : city.Name,
                            country = (city.Country == null) ? BasePage.StrEmpty : city.Country.Name
                        };

                    return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(new
                    {
                        sEcho = sEcho,
                        iTotalRecords = res.Count(),
                        iTotalDisplayRecords = iTotalDisplayRecords,
                        aaData = res.ToArray()
                    });
                }
            }
            catch (Exception exc)
            {
                return exc.ToString();
            }
        }


        /// <summary>
        /// Удаление
        /// </summary>
        /// <returns>Возвращает "ОК" или текст ошибки</returns>
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public string DeleteCityById(int id)
        {
            try
            {
                using (var cityRepository = new CityRepository())
                {
                    cityRepository.Delete(id);
                    return "OK";
                }
            }
            catch (Exception exc)
            {
                return exc.ToString();
            }
        }


        /// <summary>
        /// Получение ссылки на редактирование
        /// </summary>
        /// <param name="id"></param>
        [WebMethod]
        [ScriptMethod(UseHttpGet = false)]
        public void EditCityBy(int id)
        {
            var request = (HttpWebRequest)WebRequest.Create(AdminBasePage.UrlAdminCityEdit + "?id=" + id);
        }

        /// <summary>
        /// Получение списка
        /// </summary>
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public string GetServiceTypeBy(int sEcho, int iColumns, string sColumns, int iDisplayStart, int iDisplayLength, string sSearch, int iSortCol_0, string sSortDir_0)
        {
            try
            {
                using (var serviceTypeRepository = new ServiceTypeRepository())
                {
                    SortDir sortDir = (sSortDir_0 == SortDir.DESC.ConvertToString().ToLower()) ? SortDir.DESC : SortDir.ASC;
                    int iTotalDisplayRecords = 0;

                    string sortBy = String.Empty;

                    switch (iSortCol_0)
                    {
                        case 0:
                            sortBy = Reflector.GetPropertyName<ServiceType>(x => x.Name);
                            break;
                        default:
                            sortBy = Reflector.GetPropertyName<ServiceType>(x => x.ID);
                            break;
                    }

                    var res =
                        from serviceType in serviceTypeRepository.GetPage(iDisplayStart, iDisplayLength, sortBy, sortDir, out iTotalDisplayRecords)
                        select new
                        {
                            ID = serviceType.ID,
                            name = string.IsNullOrEmpty(serviceType.Name) ? BasePage.StrEmpty : serviceType.Name
                        };

                    return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(new
                    {
                        sEcho = sEcho,
                        iTotalRecords = res.Count(),
                        iTotalDisplayRecords = iTotalDisplayRecords,
                        aaData = res.ToArray()
                    });
                }
            }
            catch (Exception exc)
            {
                return exc.ToString();
            }
        }


        /// <summary>
        /// Удаление
        /// </summary>
        /// <returns>Возвращает "ОК" или текст ошибки</returns>
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public string DeleteServiceTypeById(int id)
        {
            try
            {
                using (var serviceTypeRepository = new ServiceTypeRepository())
                {
                    serviceTypeRepository.Delete(id);
                    return "OK";
                }
            }
            catch (Exception exc)
            {
                return exc.ToString();
            }
        }


        /// <summary>
        /// Получение ссылки на редактирование
        /// </summary>
        /// <param name="id"></param>
        [WebMethod]
        [ScriptMethod(UseHttpGet = false)]
        public void EditServiceTypeBy(int id)
        {
            var request = (HttpWebRequest)WebRequest.Create(AdminBasePage.UrlAdminServiceTypeEdit + "?id=" + id);
        }

        /// <summary>
        /// Получение списка
        /// </summary>
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public string GetServiceBy(int sEcho, int iColumns, string sColumns, int iDisplayStart, int iDisplayLength, string sSearch, int iSortCol_0, string sSortDir_0)
        {
            try
            {
                using (var serviceRepository = new ServiceRepository())
                {
                    SortDir sortDir = (sSortDir_0 == SortDir.DESC.ConvertToString().ToLower()) ? SortDir.DESC : SortDir.ASC;
                    int iTotalDisplayRecords = 0;

                    string sortBy = String.Empty;

                    switch (iSortCol_0)
                    {
                        case 0:
                            sortBy = Reflector.GetPropertyName<Service>(x => x.Name);
                            break;
                        case 2:
                            sortBy = Reflector.GetPropertyName<Service>(x => x.IsPublished);
                            break;
                        default:
                            sortBy = Reflector.GetPropertyName<Service>(x => x.ID);
                            break;
                    }

                    var res =
                        from service in serviceRepository.GetPage(iDisplayStart, iDisplayLength, sortBy, sortDir, out iTotalDisplayRecords)
                        select new
                        {
                            ID = service.ID,
                            name = string.IsNullOrEmpty(service.Name) ? BasePage.StrEmpty : service.Name,
                            parent = (service.ParentID == null) ? "-" : serviceRepository.GetParent((int)service.ParentID).Name,
                            serviceType = (service.ServiceTypes == null) ? "-" : serviceRepository.GetServiceType(service.ID),
                            published = service.IsPublished.ToText()
                        };

                    return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(new
                    {
                        sEcho = sEcho,
                        iTotalRecords = res.Count(),
                        iTotalDisplayRecords = iTotalDisplayRecords,
                        aaData = res.ToArray()
                    });
                }
            }
            catch (Exception exc)
            {
                return exc.ToString();
            }
        }


        /// <summary>
        /// Удаление
        /// </summary>
        /// <returns>Возвращает "ОК" или текст ошибки</returns>
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public string DeleteServiceById(int id)
        {
            try
            {
                using (var serviceRepository = new ServiceRepository())
                {
                    serviceRepository.Delete(id);
                    return "OK";
                }
            }
            catch (Exception exc)
            {
                return exc.ToString();
            }
        }


        /// <summary>
        /// Получение ссылки на редактирование
        /// </summary>
        /// <param name="id"></param>
        [WebMethod]
        [ScriptMethod(UseHttpGet = false)]
        public void EditServiceBy(int id)
        {
            var request = (HttpWebRequest)WebRequest.Create(AdminBasePage.UrlAdminServiceEdit + "?id=" + id);
        }

        /// <summary>
        /// Получение списка
        /// </summary>
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public string GetCurrencyBy(int sEcho, int iColumns, string sColumns, int iDisplayStart, int iDisplayLength, string sSearch, int iSortCol_0, string sSortDir_0)
        {
            try
            {
                using (var currencyRepository = new CurrencyRepository())
                {
                    SortDir sortDir = (sSortDir_0 == SortDir.DESC.ConvertToString().ToLower()) ? SortDir.DESC : SortDir.ASC;
                    int iTotalDisplayRecords = 0;

                    string sortBy = String.Empty;

                    switch (iSortCol_0)
                    {
                        case 0:
                            sortBy = Reflector.GetPropertyName<Currency>(x => x.Code);
                            break;
                        case 1:
                            sortBy = Reflector.GetPropertyName<Currency>(x => x.Name);
                            break;
                        default:
                            sortBy = Reflector.GetPropertyName<Currency>(x => x.ID);
                            break;
                    }

                    var res =
                        from currency in currencyRepository.GetPage(iDisplayStart, iDisplayLength, sortBy, sortDir, out iTotalDisplayRecords)
                        select new
                        {
                            ID = currency.ID,
                            code = string.IsNullOrEmpty(currency.Code) ? BasePage.StrEmpty : currency.Code,
                            name = string.IsNullOrEmpty(currency.Name) ? BasePage.StrEmpty : currency.Name
                        };

                    return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(new
                    {
                        sEcho = sEcho,
                        iTotalRecords = res.Count(),
                        iTotalDisplayRecords = iTotalDisplayRecords,
                        aaData = res.ToArray()
                    });
                }
            }
            catch (Exception exc)
            {
                return exc.ToString();
            }
        }


        /// <summary>
        /// Удаление
        /// </summary>
        /// <returns>Возвращает "ОК" или текст ошибки</returns>
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public string DeleteCurrencyById(int id)
        {
            try
            {
                using (var currencyRepository = new CurrencyRepository())
                {
                    currencyRepository.Delete(id);
                    return "OK";
                }
            }
            catch (Exception exc)
            {
                return exc.ToString();
            }
        }


        /// <summary>
        /// Получение ссылки на редактирование
        /// </summary>
        /// <param name="id"></param>
        [WebMethod]
        [ScriptMethod(UseHttpGet = false)]
        public void EditCurrencyBy(int id)
        {
            var request = (HttpWebRequest)WebRequest.Create(AdminBasePage.UrlAdminCurrencyEdit + "?id=" + id);
        }
    }
}
